package com.probos.bosnatuur.monitor;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class ElementCultuurhistorie extends Activity {
	
    private EditText mTitleText;
    private EditText mBodyText;
    
    private EditText mDateText;
    private EditText mTimeText;
    private Button mPickDate;
    private Button mPickTime;
    private Spinner mHoofdSpinner;
    private Spinner mSubSpinner;
    private Spinner mFunctieSpinner;
    private Spinner mVisueelSpinner;
    private Spinner mValidatieSpinner;
    private Spinner mRecorderSpinner;
    
    private Long mRowId;
//    private Long mProjectId;
    private Long mCultuurId;
    private Long mHoofd;
    private Long mSub;
    private Long mFunctie;
    private Long mVisueel;
    private String mValidatie;
    private String mRecorder;
    
    private ProjectDbAdapter mDbHelper;

    private Map<Long, String> mHoofdMap;
    private ArrayList<String> mHoofdList;

    private Map<Long, Sub> mSubMap;
    private ArrayList<Sub> mSubList;
    
    private SpinList mFunctieList;
    private SpinList mVisueelList;
    private SpinList mValidatieList;
    private SpinList mRecorderList;
    
    private Date mDatum = null;
//    private String mUserName;
    
    static final int DATE_DIALOG_ID = 0;
    static final int TIME_DIALOG_ID = 1;

    private static final String TAG = "ElementCultuurhistorie";

    public static final String PREFS_NAME = "BosNatuurPrefs"; 
    static SharedPreferences mSettings;
    SharedPreferences.Editor mEditor;

    public class SpinElement {
    	private long id;
    	private String text = "";
    	
    	public SpinElement( long _id, String _text ) {
    		id = _id;
    		text = _text;
    	}

    	public String toString() {
    		return text;
    	}

		public Object getKey() {
			return id;
		}
    }    
    
    public class Sub extends SpinElement {
    	private int hoofd;
    	private int sub;

    	public Sub( long _id, int _hoofd, int _sub, String _text ) {
    		super(_id, _text);
    		hoofd = _hoofd;
    		sub = _sub;
    	}

		public Integer getKey() {
			return sub;
		}
    }   

    public class Validatie extends SpinElement {
    	private String code;

    	public Validatie( long _id, String _code, String _text ) {
    		super(_id, _text);
    		code = _code;
    	}

		public String getKey() {
			return code;
		}
    }
    
    public class SpinList extends ArrayList<SpinElement> {

		private static final long serialVersionUID = 6206127533892927744L;

		public SpinElement findByKey(Object key) {
		    for (SpinElement s : this) { 
		        if (s.getKey() == key) {
		            return s; 
		        } 
		    } 
		    return null;  
		}
		
		public int indexOfKey(Object key) {
			int i = -1;
			int result = i;
		    for (SpinElement s : this) {
		    	i++;
		        if (s.getKey().equals(key)) {
		        	result = i; 
		        } 
		    } 
		    return result;
		}
		
		public int indexOfText(String text) {
			int i = -1;
			int result = i;
		    for (SpinElement s : this) {
		    	i++;
		        if (s.toString().equals(text)) {
		        	result = i; 
		        } 
		    } 
		    return result;
		}		
    }
    
    @Override
    protected void onPause() {
    	saveState();
    	mDbHelper.close();
    	super.onPause();
    }
    
    @Override
    protected void onResume() {
    	super.onResume();
    	mDbHelper.open();
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        mSettings = getSharedPreferences(PREFS_NAME, 0); 
//        mUserName = mSettings.getString("username", "");
        
        mDbHelper = new ProjectDbAdapter(this);
        mDbHelper.open();
        
        setContentView(R.layout.element_cultuurhistorie);
        // setTitle(R.string.element_edit);

        mTitleText = (EditText) findViewById(R.id.element_name);
        mBodyText = (EditText) findViewById(R.id.element_text);

        // capture our View elements
        mDateText = (EditText) findViewById(R.id.dateText);
        mPickDate = (Button) findViewById(R.id.pickDate);
        mTimeText = (EditText) findViewById(R.id.timeText);
        mPickTime = (Button) findViewById(R.id.pickTime);

        // add a click listener to the button
        mPickDate.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
            }
        });
        mPickTime.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(TIME_DIALOG_ID);
            }
        });
        
        mRowId = (savedInstanceState == null) ? null : (Long) savedInstanceState.getSerializable(ProjectDbAdapter.KEY_ROWID);
        if (mRowId == null) {
        	Bundle extras = getIntent().getExtras();
        	if (extras != null) {
        		if (extras.containsKey(ProjectDbAdapter.KEY_ROWID)) {
        			mRowId = extras.getLong(ProjectDbAdapter.KEY_ROWID);
        		} else {
        			if (extras.containsKey("new_id")) mRowId = extras.getLong("new_id");
        		}
        	}
        }
/*       
        Button confirmButton = (Button) findViewById(R.id.confirm);
        confirmButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
            	saveState();
            	setResult(RESULT_OK);
                finish();
            }
        });
        
        Button cancelButton = (Button) findViewById(R.id.cancel);
        cancelButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
            	setResult(RESULT_CANCELED);
                finish();
            }
        });
*/
        mHoofdSpinner = (Spinner) findViewById(R.id.spin_hoofd);
        mHoofdSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { 
            	mHoofd = id;
            	setSubSpinner();
       			if (mSub != null) {
           			Sub sub = mSubMap.get(mSub);
           			int subPosition = mSubList.indexOf(sub);
           			mSubSpinner.setSelection(subPosition);
       			}
            }
            public void onNothingSelected(AdapterView<?> parent) {
            } 
        }); 
        setHoofdSpinner();        

        mSubSpinner = (Spinner) findViewById(R.id.spin_sub);
        mSubSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            	Sub sub = (Sub) mSubSpinner.getSelectedItem();
            	mSub = (long) sub.sub;
            }
			public void onNothingSelected(AdapterView<?> parent) {
			}
        });
        
        mFunctieSpinner = (Spinner) findViewById(R.id.spin_functie);
        mFunctieSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            	SpinElement func = (SpinElement) mFunctieSpinner.getSelectedItem();
            	mFunctie = (Long) func.getKey();
            }
			public void onNothingSelected(AdapterView<?> parent) {
			}
        });
        setFunctieSpinner();

        mVisueelSpinner = (Spinner) findViewById(R.id.spin_visueel);
        mVisueelSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            	SpinElement elm = (SpinElement) mVisueelSpinner.getSelectedItem();
            	mVisueel = (Long) elm.getKey();
            }
			public void onNothingSelected(AdapterView<?> parent) {
			}
        });
        setVisueelSpinner();

        mValidatieSpinner = (Spinner) findViewById(R.id.spin_validatie);
        mValidatieSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            	Validatie elm = (Validatie) mValidatieSpinner.getSelectedItem();
            	mValidatie = elm.getKey();
            }
			public void onNothingSelected(AdapterView<?> parent) {
			}
        });
        setValidatieSpinner();
        
        mRecorderSpinner = (Spinner) findViewById(R.id.spin_recorder);
        mRecorderSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            	SpinElement elm = (SpinElement) mRecorderSpinner.getSelectedItem();
            	mRecorder = elm.toString();
            }
			public void onNothingSelected(AdapterView<?> parent) {
			}
        });
        setRecorderSpinner();

        populateFields();
    }

    private void setHoofdSpinner() {
        mHoofdMap = new LinkedHashMap<Long, String>();
        Cursor hc = mDbHelper.HoofdCategorie();
        if (hc != null) {
        	mHoofdMap.put((long) -1, "");
        	while(hc.moveToNext()) {
        		long key = hc.getLong(hc.getColumnIndex(ProjectDbAdapter.KEY_ROWID));
        		String value = hc.getString(hc.getColumnIndex(ProjectDbAdapter.KEY_DESCRIPTION));        		
        		mHoofdMap.put(key, value);
        	}
        }
        hc.close();
        mHoofdList = new ArrayList<String>(mHoofdMap.values());
        
        ArrayAdapter<Object> a = new ArrayAdapter<Object>(this, android.R.layout.simple_spinner_item, android.R.id.text1, mHoofdList.toArray());      
        a.setDropDownViewResource(android.R.layout.simple_spinner_item);
        mHoofdSpinner.setAdapter(a);    	
    }

    private void setSubSpinner() {
    	Sub sub;
    	mSubMap = new LinkedHashMap<Long, Sub>();
        Cursor sc = mDbHelper.SubCategorie(mHoofd);
        if (sc != null) {
        	sub = new Sub(0,0,0,"");
        	mSubMap.put((long) -1, sub);
        	while(sc.moveToNext()) {
        		long id = sc.getLong(sc.getColumnIndex(ProjectDbAdapter.KEY_ROWID));
        		int hoofd = sc.getInt(sc.getColumnIndex("hoofd"));
        		int key = sc.getInt(sc.getColumnIndex("sub"));
        		String value = sc.getString(sc.getColumnIndex(ProjectDbAdapter.KEY_DESCRIPTION));
        		sub = new Sub(id, hoofd, key, value);
        		mSubMap.put((long)key, sub);
        	}
        }
        sc.close();
        mSubList = new ArrayList<Sub>(mSubMap.values());
        
        ArrayAdapter<Object> a = new ArrayAdapter<Object>(this, android.R.layout.simple_spinner_item, android.R.id.text1, mSubList.toArray());                
        a.setDropDownViewResource(android.R.layout.simple_spinner_item);
        mSubSpinner.setAdapter(a);    	
    }

    private void setFunctieSpinner() {
    	mFunctieList = new SpinList();
        SpinElement elm =  new SpinElement(0,"");
        
        Cursor c = mDbHelper.FunctieCursor();
        if (c != null) {
        	mFunctieList.add(elm);
        	while(c.moveToNext()) {
        		long key = c.getLong(c.getColumnIndex(ProjectDbAdapter.KEY_ROWID));
        		String value = c.getString(c.getColumnIndex(ProjectDbAdapter.KEY_DESCRIPTION));
        		elm =  new SpinElement(key,value);
        		mFunctieList.add(elm);
        	}
        }
        c.close();
        
        ArrayAdapter<Object> a = new ArrayAdapter<Object>(this, android.R.layout.simple_spinner_item, android.R.id.text1, mFunctieList.toArray());      
        a.setDropDownViewResource(android.R.layout.simple_spinner_item);
        mFunctieSpinner.setAdapter(a);    	
    }

    private void setVisueelSpinner() {
    	mVisueelList = new SpinList();
        SpinElement elm =  new SpinElement(0,"");
        
        Cursor c = mDbHelper.VisueelCursor();
        if (c != null) {
        	mVisueelList.add(elm);
        	while(c.moveToNext()) {
        		long key = c.getLong(c.getColumnIndex(ProjectDbAdapter.KEY_ROWID));
        		String value = c.getString(c.getColumnIndex(ProjectDbAdapter.KEY_DESCRIPTION));
        		elm =  new SpinElement(key,value);
        		mVisueelList.add(elm);
        	}
        }
        c.close();
        
        ArrayAdapter<Object> a = new ArrayAdapter<Object>(this, android.R.layout.simple_spinner_item, android.R.id.text1, mVisueelList.toArray());      
        a.setDropDownViewResource(android.R.layout.simple_spinner_item);
        mVisueelSpinner.setAdapter(a);    	
    }

    private void setValidatieSpinner() {
    	mValidatieList = new SpinList();
    	Validatie elm =  new Validatie(0,"","");
        
        Cursor c = mDbHelper.ValidatieCursor();
        if (c != null) {
        	mValidatieList.add(elm);
        	while(c.moveToNext()) {
        		Long id = c.getLong(c.getColumnIndex(ProjectDbAdapter.KEY_ROWID));
        		String key = c.getString(c.getColumnIndex("code"));
        		String value = c.getString(c.getColumnIndex(ProjectDbAdapter.KEY_DESCRIPTION));
        		elm =  new Validatie(id,key,value);
        		mValidatieList.add(elm);
        	}
        }
        c.close();
        
        ArrayAdapter<Object> a = new ArrayAdapter<Object>(this, android.R.layout.simple_spinner_item, android.R.id.text1, mValidatieList.toArray());      
        a.setDropDownViewResource(android.R.layout.simple_spinner_item);
        mValidatieSpinner.setAdapter(a);    	
    }

    private void setRecorderSpinner() {
    	mRecorderList = new SpinList();
    	SpinElement elm =  new SpinElement(0,"");
        
        Cursor c = mDbHelper.fetchAllUsers();
        if (c != null) {
        	while(c.moveToNext()) {
        		Long id = c.getLong(c.getColumnIndex(ProjectDbAdapter.KEY_ROWID));
        		String value = c.getString(c.getColumnIndex(ProjectDbAdapter.KEY_NAME));
        		elm =  new SpinElement(id, value);
        		mRecorderList.add(elm);
        	}
        }
        c.close();
        
        ArrayAdapter<Object> a = new ArrayAdapter<Object>(this, android.R.layout.simple_spinner_item, android.R.id.text1, mRecorderList.toArray());      
        a.setDropDownViewResource(android.R.layout.simple_spinner_item);
        mRecorderSpinner.setAdapter(a);    	
    }
    
    private void populateFields() {
        if (mRowId != null) {

       		Cursor ch = mDbHelper.findCultuurHistorie(mRowId);
       		if (ch != null) {
       			if (ch.moveToFirst()) {
       				mCultuurId = ch.getLong(ch.getColumnIndexOrThrow(ProjectDbAdapter.KEY_ROWID));
           			mHoofd = ch.getLong(ch.getColumnIndexOrThrow("hoofd"));
           			mSub = ch.getLong(ch.getColumnIndexOrThrow("sub"));
           			mFunctie = ch.getLong(ch.getColumnIndexOrThrow("functie1"));
           			mVisueel = ch.getLong(ch.getColumnIndexOrThrow("visueel"));
           			mValidatie = ch.getString(ch.getColumnIndexOrThrow("validatie"));
           			mRecorder = ch.getString(ch.getColumnIndexOrThrow("opnemer"));
           			
           			if (mHoofd != null) {
	           			String strHoofd = mHoofdMap.get(mHoofd);
	           			int hoofdPosition = mHoofdList.indexOf(strHoofd);
	           			mHoofdSpinner.setSelection(hoofdPosition);
           			}
           			if (mFunctie != null) {		           			
	           			int i = mFunctieList.indexOfKey(mFunctie);
	           			mFunctieSpinner.setSelection(i);
           			}
           			if (mVisueel != null) {		           			
	           			int i = mVisueelList.indexOfKey(mVisueel);
	           			mVisueelSpinner.setSelection(i);
           			}
           			if (mValidatie != null) {		           			
	           			int i = mValidatieList.indexOfKey(mValidatie);
	           			mValidatieSpinner.setSelection(i);
           			}
           			if (mRecorder != null) {          			
	           			int i = mRecorderList.indexOfText(mRecorder);
	           			mRecorderSpinner.setSelection(i);
           			}
           			
           			EditText txtAanlegjaar = (EditText) findViewById(R.id.element_aanlegjaar);
           			int i = ch.getColumnIndexOrThrow("aanlegjaar");	           			
           			if (!ch.isNull(i)) {
	           			Integer jaar = ch.getInt(i);
	           			txtAanlegjaar.setText(jaar.toString());	           				
           			}
           			
           			EditText txtPeriode = (EditText) findViewById(R.id.element_periode);
           			txtPeriode.setText(ch.getString(ch.getColumnIndexOrThrow("periode")));	           			
           			
           			EditText txtBron = (EditText) findViewById(R.id.element_source);
           			txtBron.setText(ch.getString(ch.getColumnIndexOrThrow("bron")));	           			
           			
               		String strDatum = ch.getString(ch.getColumnIndexOrThrow("datum"));
     				mDatum = ProjectDbAdapter.DBStringToDate(strDatum);
     				
     				ch.close();
       			} else {
       				Cursor elm = mDbHelper.fetchElement(mRowId);
       				
               		String strDatum = elm.getString(elm.getColumnIndexOrThrow(ProjectDbAdapter.KEY_DATE));
     				mDatum = ProjectDbAdapter.DBStringToDate(strDatum);      				
     				mRecorder = elm.getString(elm.getColumnIndexOrThrow(ProjectDbAdapter.KEY_DATE));
       				
     				elm.close();
       			}
       		}
        }
      	updateDisplay();        
    }

    // updates the date in the TextView
    private void updateDisplay() {
    	if (mDatum != null) {
	        mDateText.setText(DateFormat.getDateFormat(this).format(mDatum));
	        mTimeText.setText(DateFormat.getTimeFormat(this).format(mDatum));
    	}
    }
    
    private void saveState() {

    	ContentValues values = new ContentValues();
    	values.put("element_id", mRowId);      	
    	values.put("hoofd", mHoofd);
    	values.put("sub", mSub);
    	values.put("functie1", mFunctie);
    	values.put("visueel", mVisueel);
    	values.put("validatie", mValidatie);
    	
		EditText txtAanlegjaar = (EditText) findViewById(R.id.element_aanlegjaar);
		String jaar = txtAanlegjaar.getText().toString();
		if (jaar.trim().length() == 0) {
			values.putNull("aanlegjaar");
		} else {
			values.put("aanlegjaar", new Integer(jaar));
		}
		
		EditText txtPeriode = (EditText) findViewById(R.id.element_periode);
		values.put("periode", txtPeriode.getText().toString());
		
		EditText txtBron = (EditText) findViewById(R.id.element_source);
		values.put("bron", txtBron.getText().toString());
		
		values.put("opnemer", mRecorder);
		if (mDatum != null) {
			values.put("datum", ProjectDbAdapter.DateToDBString(mDatum));
		}
	   	
//		if (!mDbHelper.isOpen()) {
//    		mDbHelper.open();
//    	}
        
        if (mCultuurId == null) {
            long id = mDbHelper.createCultuurHistorie(values);
            if (id > 0) mCultuurId = id;
        } else {
            mDbHelper.updateCultuurHistorie(mCultuurId, values);
        }
    }
    
    // the callback received when the user "sets" the date in the dialog
    private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {
    			public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {                    
                    mDatum.setYear(year-1900);
                    mDatum.setMonth(monthOfYear);
                    mDatum.setDate(dayOfMonth);                    
                    updateDisplay();
                }
            };
            
	private OnTimeSetListener mTimeSetListener =
	        new TimePickerDialog.OnTimeSetListener() {
				public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
	                mDatum.setHours(hourOfDay);
	                mDatum.setMinutes(minute);
	                updateDisplay();
				}
	        };
	
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DATE_DIALOG_ID:
            return new DatePickerDialog(this, mDateSetListener, mDatum.getYear()+1900, mDatum.getMonth(),mDatum.getDate());
        case TIME_DIALOG_ID:
            return new TimePickerDialog(this, mTimeSetListener, mDatum.getHours(), mDatum.getMinutes(),true);
        }
        return null;
    }
    
    @Override     
    protected void onDestroy() {
        mDbHelper.close();
        super.onDestroy();
    }
}
